﻿using System.Windows.Input;
using Oxage.Models;

namespace Oxage.Services
{
	public class KeyboardService
	{
		public static KeyboardMapper Mapper
		{
			get
			{
				if (mapper == null)
				{
					//Register default key mappings
					mapper = new KeyboardMapper();
					mapper.Add(Key.F5, ModifierKeys.None, () => StartContinueDebug()); //TODO: WorkspaceService.Context == Edit | Debug
					mapper.Add(Key.F5, ModifierKeys.Shift, () => StopDebug());
					mapper.Add(Key.F3, ModifierKeys.None, () => DialogService.FindNext());
					mapper.Add(Key.F, ModifierKeys.Control, () => DialogService.Find());
					mapper.Add(Key.H, ModifierKeys.Control, () => DialogService.Replace());
					mapper.Add(Key.G, ModifierKeys.Control, () => DialogService.JumpToLine());
					mapper.Add(Key.N, ModifierKeys.Control, () => DocumentService.NewFile());
					mapper.Add(Key.O, ModifierKeys.Control, () => DocumentService.OpenFile());
					mapper.Add(Key.S, ModifierKeys.Control, () => DocumentService.SaveFile(false));
					mapper.Add(Key.R, ModifierKeys.Control, () => SimulatorService.Refresh());
					mapper.Add(Key.B, ModifierKeys.Control | ModifierKeys.Shift, () => BuildService.CheckCode());
				}

				return mapper;
			}
		}
		private static KeyboardMapper mapper;

		public static bool KeyDown(object sender, Key key)
		{
			bool handled = false;
			//bool shift = (Keyboard.Modifiers & ModifierKeys.Shift) > 0;
			//bool ctrl = (Keyboard.Modifiers & ModifierKeys.Control) > 0;
			//bool alt = (Keyboard.Modifiers & ModifierKeys.Alt) > 0;
			//bool win = (Keyboard.Modifiers & ModifierKeys.Windows) > 0;

			var action = Mapper.Find(key, Keyboard.Modifiers);
			if (action != null)
			{
				action();
				handled = true;
			}

			return handled;
		}

		protected static void StartContinueDebug()
		{
			var debugger = DebugService.CurrentProjectDebugger;
			if (debugger != null)
			{
				if (debugger.IsDebugging)
				{
					debugger.Continue();
				}
				else
				{
					debugger.Start();
				}
			}
		}

		protected static void StopDebug()
		{
			var debugger = DebugService.CurrentProjectDebugger;
			if (debugger != null)
			{
				debugger.Stop();
			}
		}
	}
}
